﻿using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Drawing; 
using System.IO; 
using System.Drawing.Imaging;

namespace DotNet.Common
{
    /// <summary> 
    /// 上传类 
    /// </summary> 
    public class UploadFiles
    {
        public UploadFiles()
        { }
        /// <summary> 
        /// 允许文件上传的类型枚举 
        /// </summary> 
        public enum FileType
        { jpg, gif, bmp, png, txt, doc, xls, wps, xml, ppt, html, wmv, mp4, avi, rm, rmvb, flv, swf, asf, rar, zip,chm }
        public enum ImageType
        { jpg, gif, bmp, png }
        public enum TxtType
        { txt, doc, xls, wps, xml, ppt, html,chm }
        public enum VideoType
        { wmv, mp4, avi, rm, rmvb, flv, swf, asf }
        public enum ZipType
        { rar, zip }

        #region 取得文件后缀
        /// <summary> 
        /// 取得文件后缀 
        /// </summary> 
        /// <param name="filename">文件名称</param> 
        /// <returns></returns> 
        public static string GetFileExtends(string filename)
        {
            string ext = null;
            if (filename.IndexOf('.') > 0)
            {
                string[] fs = filename.Split('.');
                ext = fs[fs.Length - 1];
            }
            return ext;
        }
        #endregion

        #region 检测文件是否合法
        /// <summary> 
        /// 检测上传文件是否合法 
        /// </summary> 
        /// <param name="fileExtends">文件后缀名</param> 
        /// <returns></returns> 
        public static bool CheckFileExtends(string fileExtends, string fileTpye)
        {
            bool status = false;
            fileExtends = fileExtends.ToLower();

            string[] fe;
            switch (fileTpye)
            {
                case "ImageType":
                    fe = Enum.GetNames(typeof(ImageType));
                    break;
                case "TxtType":
                    fe = Enum.GetNames(typeof(TxtType));
                    break;
                case "VideoType":
                    fe = Enum.GetNames(typeof(VideoType));
                    break;
                case "ZipType":
                    fe = Enum.GetNames(typeof(ZipType));
                    break;
                case "FileType":
                    fe = Enum.GetNames(typeof(FileType));
                    break;
                default:
                    fe = Enum.GetNames(typeof(FileType));
                    break;

            }
            // string[] fe = Enum.GetNames(typeof(FileType));
            for (int i = 0; i < fe.Length; i++)
            {
                if (fe[i].ToLower() == fileExtends)
                {
                    status = true;
                    break;
                }
            }
            return status;
        }
        #endregion

        #region 保存文件
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="page">this</param>
        /// <param name="fpath">全路径,Server.MapPath()</param>
        /// <param name="myFileUpload">上传控件</param>
        /// <param name="fileSize">文件大小,以K为单位</param>
        /// <param name="fileTpye">ImageType,TxtType,VideoType,ZipType,FileType </param>
        /// <returns>保存文件</returns>
        public static string FileSave(System.Web.UI.Page page, string fpath, FileUpload myFileUpload, int fileSize, string fileTpye)
        {
            string s = "";
            string fileExtends = "";
            string fileName = myFileUpload.FileName;

            if (fileName != "")
            {
                //取得文件后缀 
                fileExtends = UploadFiles.GetFileExtends(fileName);
                if (!UploadFiles.CheckFileExtends(fileExtends, fileTpye))
                {
                    DotNet.Common.MessageBox.Show(page, "上传文件类型不合法");
                    return "";
                }
                //上传文件大小
                if (myFileUpload.PostedFile.ContentLength > fileSize * 1024)
                {
                    DotNet.Common.MessageBox.Show(page, "上传文件不能大于" + fileSize.ToString() + "K,请处理后上传!");
                    return "";
                }
                //生成新文件名 
                System.Text.StringBuilder NewFileName = new System.Text.StringBuilder();
                //格式化到毫秒 + 4位随机数
                string newstr = DateTime.Now.ToString("yyyyMMddhhmmssfff");
                //生成随机数
                Random rnd = new Random();
                int randomInt = rnd.Next(1000, 9999);
                newstr += randomInt.ToString();

                //NewFileName.Append(DateTime.Now.Year.ToString());
                //NewFileName.Append(DateTime.Now.Month.ToString());
                //NewFileName.Append(DateTime.Now.Day.ToString());
                //NewFileName.Append(DateTime.Now.Hour.ToString());
                //NewFileName.Append(DateTime.Now.Minute.ToString());
                //NewFileName.Append(DateTime.Now.Second.ToString());
                NewFileName.Append(newstr);
                NewFileName.Append(".");// +"." + fileExtends;
                NewFileName.Append(fileExtends);
                s = NewFileName.ToString();
                string file = fpath + "\\" + s;
                try
                {
                    myFileUpload.SaveAs(file);
                    // DotNet.Common.MessageBox.Show(page, "上传成功!");
                }
                catch (Exception ee)
                {
                    // throw new Exception(ee.ToString());
                    DotNet.Common.MessageBox.Show(page, "上传失败!");
                    return "";
                }
            }
            return s;
        }
        #endregion

        #region 加入文字水印
        /// <summary> 
        /// 加入文字水印 
        /// </summary> 
        /// <param name="fileName">文件名称路径(全路径)</param> 
        /// <param name="text">文件</param> 
        public static void AddTextToImg(string fileName, string text)
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("文件不存在");
            }
            if (text == string.Empty)
            {
                return;
            }
            //判断文件类型是否为图像类型 
            System.Drawing.Image image = System.Drawing.Image.FromFile(fileName);
            Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
            Graphics g = Graphics.FromImage(bitmap);
            float fontSize = 12.0f;//字体大小 
            float textWidth = text.Length * fontSize;//文本的长度 
            //下面定义一个矩形区域,以后在这个矩形里面画上白底黑字 
            float rectX = 0;
            float rectY = 0;
            float rectWidth = text.Length * (fontSize + 8);
            float rectHeight = fontSize + 8;
            //声明矩形域 
            RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
            Font font = new Font("宋体", fontSize);//定义字体 
            Brush whiteBrush = new SolidBrush(Color.White);//白笔刷,画文字用 
            Brush blackBrush = new SolidBrush(Color.Black);//黑笔刷，画背景用 
            g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
            g.DrawString(text, font, whiteBrush, textArea);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            //输出处理后的图像，这里为了演示方便，我将图片显示在页面中了 
            //Response.Clear(); 
            //Response.ContentType = "image/jpeg"; 
            //Response.BinaryWrite(ms.ToArray()); 
            g.Dispose();
            bitmap.Dispose();
            image.Dispose();
        }
        #endregion

        #region 生成缩略图 MakeSmallImage
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式 HW指定高宽缩放（可能变形） "H"://指定高，宽按比例 "W"://指定宽，高按比例 "Cut"://指定高宽裁减（不变形）  </param>    
        public static void MakeSmallImage(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        #endregion 

    }

}
